package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.feigns.article.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    ApArticleMapper apArticleMapper;
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Autowired
    AdminFeign adminFeign;

    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {
        //查询最近5天的文章数据
        String date = LocalDateTime.now().minusDays(5).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        List<ApArticle> apArticleList = apArticleMapper.loadArticleListByTime(date);
        if(apArticleList==null||apArticleList.size()==0){
            log.info("计算热点文章服务报错，查询文章数据失败");
            return;
        }
        //计算文章的分值
        List<HotArticleVo> hotArticleVoList = computeArticleScore(apArticleList);
        //根据分值为各个频道缓存前三十的文章
        cacheTagToRedis(hotArticleVoList);
    }

    /**
     * 根据分值为各个频道缓存前三十的文章
     * @param hotArticleVoList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        //获取所有频道id
        ResponseResult responseResult = adminFeign.selectAllChannel();
        if(responseResult.getCode()==0){
            List<AdChannel> adChannels = JSONArray.parseArray(JSON.toJSONString(responseResult.getData()), AdChannel.class);
            //根据频道id遍历获取前三十
            for (AdChannel adChannel : adChannels) {
                List<HotArticleVo> hotArticleVos = hotArticleVoList.stream().filter(hotArticleVo -> hotArticleVo.getChannelId() == adChannel.getId())
                        .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                        .limit(30)
                        .collect(Collectors.toList());
                //将文章存入到redis里
                redisTemplate.opsForValue().set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE+adChannel.getId(),JSON.toJSONString(hotArticleVos));
            }
        }
        //将推荐页数据存入到redis中
        List<HotArticleVo> hotArticleVos = hotArticleVoList.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
        //将文章存入到redis里
        redisTemplate.opsForValue().set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG,JSON.toJSONString(hotArticleVos));
    }

    /**
     * 计算所有文章得分
     * @param apArticleList
     */
    private List<HotArticleVo> computeArticleScore(List<ApArticle> apArticleList) {
        return apArticleList.stream().map(apArticle -> {
            HotArticleVo hotArticleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticle,hotArticleVo);
            //计算文章得分
            computeScore(hotArticleVo);
            return hotArticleVo;
        }).collect(Collectors.toList());
    }

    /**
     * 计算文章得分
     * @param hotArticleVo
     * @return
     */
    private void computeScore(HotArticleVo hotArticleVo) {
        Integer score=0;
        if(hotArticleVo.getViews()!=null){
            score +=hotArticleVo.getViews()* ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }
        if(hotArticleVo.getLikes()!=null){
            score +=hotArticleVo.getLikes()* ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(hotArticleVo.getComment()!=null){
            score +=hotArticleVo.getComment()* ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(hotArticleVo.getCollection()!=null){
            score +=hotArticleVo.getCollection()* ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        hotArticleVo.setScore(score);
    }
}
